<?php

    /**
    * Игра «Кладоискатель»
    *  - Количество ячеек с призами вычитывается при создании новой игры
    */

    $mikron->Page->StartBody();
    
    global $mikron;
    $auth = $mikron->Site->auth;

    $gameform = null;
    $gameFormID = 2001;
    $game_over = false; // на игровом поле больше нет неоткрытых лунок, т.е. игра завершена
    $fields_count = 100;
    $game; // = TREASURE_GAME;

    if(!isset($_GET['ajax']))
    {
        $mikron->CSS->AddFile(dirname(__FILE__)."/style.css", "Current game style");
    }

    // Запуск формы
    try
    {
        $gameform = new game_form($gameFormID);
        $gameform->addIntValue("field", true);
        $gameform->addIntValue("gameid", true);
        $gameform->AddStatus(98, "Выбранное Вами место уже выкопано ранее.");
        $gameform->AddStatus(99, "Выбранное Вами место уже выкопано ранее.");
        $gameform->AddButton("play_grey", 1, "Играть", null, null, true);
        $gameform->AddButton("playbutton", 2, "Играть", "#", "onclick='return PlayGame();'", false, false);
        $gameform->AddButton("waitimage", 44, "<img src='/mikron/sites/7chances2/images/wait.gif' alt='wait'>", "#", null, false, false);
        $gameform->start();
    }
    catch(Exception $ex)
    {
        $message = $ex->getMessage();
        echo "{{nicewindow style=_error caption=Ошибка}}$message{{/nicewindow}}";
        $mikron->Page->EndBody();
        return;
    }

    $gameform->begin();
        // игрок сделал ставку и сделал ход
        $executed = $gameform->IsExecuted();
        // Если игра сыграна
        if($executed)
        {
            HisPlay();
        }
        $rate = $gameform->rate;
        $gm = getActiveGame();
        if($auth->cabinet->$rate->value < 1)
        {
            // $gameform->Status = 1;
            /* ?>{{nicewindow style=error caption=Внимание}}У Вас недостаточно «шансов» для игры.{{/nicewindow}}<?php */
        }
        else
        {
            
        }
        DrawGame($gm);
    $gameform->end($gm);

    // игра сыграна
    function HisPlay()
    {
        global $mikron, $auth, $gameform;
        $field = (int)$gameform->field;
        if(is_null($field))
        {
            return false;
        }
        $gameID = (int)$gameform->gameid;
        $rate = $gameform->rate;
        $cab = $auth->cabinet;
        $cabid = $cab->id;
        $game = new TREASURE_GAME($gameID);
        $prize = false;
        $already_used = false;
        $selected_treasure = null;
        foreach ($game->treasures->value as $treasure)
        {
            if($treasure->position->value == $field)
            {
                $selected_treasure = $treasure;
                if(!$selected_treasure->used->value)
                {
                    $prize = $selected_treasure->prize->value;
                }
                else
                {
                    $already_used = true;
                }
                break;
            }
        }
        if($already_used)
        {
            // Место уже выкопано
            $gameform->Status = 99;
        }
        else
        {
            try
            {
                $gameform->Status = $prize?2:3;
                $foplog = $gameform->Played($cab, $prize, 1, 10);
                if(is_null($foplog))
                {
                    return false;
                }
                else
                {
                    $selected_treasure->used->value = 1;
                    $selected_treasure->cabinet->value = $cab->id;
                    $mikron->EntityManager->Save(Array($foplog, $cab, $selected_treasure));
                    return true;
                }
            }
            catch(Exception $ex)
            {
            }
        }
        return false;
    }
    
    function getActiveGame()
    {
        global $mikron, $fields_count, $gameform;
        $rates = Array("bronze"=>1,"silver"=>2,"gold"=>3,"platinum"=>4);
        // Фильтр даты - $dtcond = "DAY(`dt`) = ".date("d", $dt)." AND MONTH(`dt`)=".date("m", $dt)." AND YEAR(`dt`)=".date("Y", $dt);
        $ratecode = $gameform->rate;
        $rate = $rates[$ratecode];
        // фильтр ставки и признака завершенности
        $cond = "`finish` = 0 AND `rate` = $rate";
        $games = $mikron->Queries->Query("TREASURE_GAME", null, $cond);
        $neednewgame = $games->count() == 0;

        if(!$neednewgame)
        {
            $game = $games->fetch();
            $id = $game->id;
            $neednewgame = $mikron->EntityManager->QueryCount('TREASURE_FIELD', null, "`game`=$id AND `used`=0 AND `prize`=1") < 1;
        }

        // Если не требуется создать игру
        if(!$neednewgame)
        {
            return $game;
        }
        else
        {
            $sf = $mikron->Site->getSettings();
            $prize_count = $sf->$ratecode->value;
            // Создание новой игры
            $game = new TREASURE_GAME();
            $game->rate->value = $rate;
            $mikron->EntityManager->Save(Array($game), false);
            try
            {
                $saved_items = Array();
                $ar = Array();
                for($i=0; $i<$fields_count; $i++)
                {
                    $ar[] = $i;
                }
                shuffle($ar);
                for($i = 0; $i < $fields_count; $i++)
                {
                    $prize_field  = new TREASURE_FIELD();
                    $prize_field->game->value = $game->id;
                    $prize_field->position->value = $ar[$i];
                    if($i < $prize_count)
                    {
                        $prize_field->prize->value = 1;
                    }
                    $saved_items[] = $prize_field;
                }
                asort($saved_items);
                $mikron->EntityManager->Save($saved_items);
                return new TREASURE_GAME($game->id);
            }
            catch(Exception $ex)
            {
                /* echo $ex->getMessage(); */
            }
        }
    }

    function DrawGame($game)
    {
        // echo $_SERVER['REQUEST_URI'];
        global $mikron, $gameform;
        $rate = $gameform->rate;
        $mikron->TemplateMaker->smarty->assign('treasures', $game);
        ?>
        <script src="script.js" type="text/javascript"></script>
        <div class="treasure_field_box" id="treasure_field_box">
            <div class="treasure_field">
                {{table columns=10
                        entity=TREASURE_FIELD
                        where="`game`=<?php echo $game->id; ?>"
                        maxitems=100
                        cellspacing=0
                        cellpadding=0}}
            </div>
        </div>
        <?php
    }

$mikron->Page->EndBody(); ?>